package com.banciyuan.bcywebview.biz.post.write;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by squall on 2016/2/22.
 */
public class EditArticleActivity extends WriteArticleActivity {

    private DetailType detailData;
    private final static int NOEDIT = 4301;

    @Override
    protected void initArgs() {
        super.initArgs();
        edit = true;
        detailData = (DetailType) getIntent().getSerializableExtra("edit_data");
    }

    @Override
    protected void initUi() {
        super.initUi();
        getEdit();
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                getEdit();
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void getEdit() {
        String url = HttpUtils.BASE_URL + NovelApi.getEditnovel();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.WPID, detailData.getWp_id()));
        pairs.add(new BcyPair(HttpUtils.RPID, detailData.getRp_id()));
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, EditArticleActivity.this)) {
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        postItem = gson.fromJson(result.toString(), new TypeToken<PostItem>() {
                        }.getType());
                        renderData();
                    } else {
                        int status = jsonObject.getInt(HttpUtils.UPLOAD_STATUS);
                        if (status == NOEDIT) {
                            mProgressbarHelper.onNodata(getString(R.string.no_edit));
                        }
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    private void renderData() {
        articleTitle.setText(postItem.getTitle().toString());
        StringBuffer sb = new StringBuffer();
        for (String s : postItem.getContent()) {
            sb.append(Html.fromHtml(s) + "\n");
        }
        articleContent.setText(sb);
        init = true;
        mProgressbarHelper.onSuccess();
    }


    @Override
    protected void initActionbar() {
        super.initActionbar();
        mActionbarHelper.setTitle(getString(R.string.edit_write));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_action_bar_home_text_item:
                if (checkSaveButton()) {
                    getPostJson();
                    Intent intent = new Intent(this, WriteEditActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                    intent.putExtra("tags", tag);
                    intent.putExtra("tag_array", (Serializable) tag_array);
                    intent.putExtra("detail", detailData);
                    startActivityForResult(intent, GO_POSTWRITE);
                }
                break;
        }
    }

    @Override
    public void onBackClick() {
        finishActivity();
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    private void finishActivity() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.not_save_warn))
                .setActionString(getString(R.string.continue_post))
                .setCancelString(getString(R.string.cancel_post))
                .setCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).create().show();
    }

    /**
     @Override protected void initAction() {
     articleTitle.addTextChangedListener(new OnTextChangeListener() {
     @Override public void afterTextChanged(Editable editable) {
     showTitleLength(editable.toString().length());
     }
     });

     articleContent.addTextChangedListener(new OnTextChangeListener() {
     @Override public void afterTextChanged(Editable editable) {
     showContentLength(editable.toString().length());
     }

     @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
     if (init) {
     if (before == 0 && count > 0) {
     //单纯添加文字
     changeWordList(s.subSequence(start, start + count), start, true);
     } else if (count > 0 && before > 0) {
     //替换文字的文本
     changeWordList(s.subSequence(start, start + count), start, true);
     }
     }

     }

     @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
     if (init) {
     if (count > 0 && after == 0) {
     //单纯删除文字
     changeWordList(s.subSequence(start, start + count), start, false);
     } else if (count > 0 && after > 0) {
     //替换文字被替换的文本
     changeWordList(s.subSequence(start, start + count), start, false);
     }
     }
     }
     });
     }*/

    /**
     * protected void changeWordList(CharSequence s, int start, boolean plus) {
     * try {
     * if (!clist.isEmpty()) {
     * if (plus) {
     * int plus_length = 0;
     * for (int i = 0; i < clist.size(); i++) {
     * if (start - plus_length <= clist.get(i).getContent().length()) {
     * clist.get(i).setContent(new StringBuffer(clist.get(i).getContent()).insert(start - plus_length, s).toString());
     * break;
     * }
     * plus_length += clist.get(i).getContent().length();
     * }
     * } else {
     * int minus_length = s.length();
     * int index = 0;
     * int total_size = 0;
     * for (; index < clist.size(); index++) {
     * total_size += clist.get(index).getContent().length();
     * if (start <= total_size) {
     * start = start - total_size + clist.get(index).getContent().length();
     * break;
     * }
     * }
     * for (int i = index; i < clist.size(); i++) {
     * int end_index = start + minus_length > clist.get(i).getContent().length() ? clist.get(i).getContent().length() : start + minus_length;
     * clist.get(i).setContent(new StringBuffer(clist.get(i).getContent()).delete(start, end_index).toString());
     * minus_length = minus_length - end_index + start;
     * if (minus_length == 0) {
     * break;
     * }
     * start = 0;
     * }
     * }
     * } else {
     * clist.add(new ChartperInfo(s.toString()));
     * }
     * <p/>
     * } catch (Exception e) {
     * exception = true;
     * e.printStackTrace();
     * }
     * }
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}
